<?php

/*
 * To change this template, choose Tools | Templates
* and open the template in the editor.
*/

class HT_Model_administrator_models_seopage extends Zend_Db_Table {//ten class fai viet hoa

	protected $_db;

	public function __construct() {
		$this->_name = "seo_page";
		$this->_db = Zend_Registry::get('dbMain');
		parent::init();
	}

	public function updateIndexing(){
		/*
		 * Có thể trong quá trình làm, test nên chỉ số visited đã lên 1 hoặc 2
		* Sau đó google đọc qua một lần và visited lên một chút.
		* Nếu google index thực sự thì visted sẽ lên nhiều hơn.
		* */
		$sql = "UPDATE seo_page SET is_google_index = 1, priority = 1 WHERE visited > 5 AND reference_news_id >0";
		$this->_db->query($sql);
	}

	public function updateVisisted($seopageId){
		$sql = "UPDATE seo_page SET visited = visited + 1 WHERE seopage_id = ?";
		$this->_db->query($sql,array($seopageId));
	}

	public function resendGoogle($ids){
		@$auth 			= Zend_Auth::getInstance();
		$user 			= @$auth->getStorage()->read();
		$wishid			= @$user->wishid;
		foreach((array)$ids as $id){
			$data = array('admin_update_id'=>$wishid,'date_updated'=>date('Y-m-d H:i:s'));
			$this->update($data, "seopage_id=".$id);
		}
	}

	public function buildRSS(){
		$objConvert = new HT_Model_administrator_models_convert();
		$newsList = $this->_getNewsForRSS();
		$data = '<?xml version="1.0" encoding="UTF-8" ?>'."\r\n";
		$data .= '<rss version="2.0">'."\r\n\r\n";

		$data .= '<channel>'."\r\n";
		$data .= '<title>Trang chủ mạng xã hội tư vấn và chăm sóc sức khỏe Wish</title>'."\r\n";
		$data .= '<link>http://wish.vn/mang-xa-hoi-tu-van-cham-soc-suc-khoe-wish.html</link>'."\r\n";
		$data .= '<description>Mạng xã hội y tế- Nơi giao lưu, kết nối chia sẻ giữa các bà bầu, cũng như nhận các tư vấn trực tuyến từ các chuyên gia và cộng đồng Wish qua chat, e-mail, giải trí sau ngày làm việc với ảnh vui, blog và xã luận, giải trí thư giãn online, mạng lưới thông tin cập nhật</description>'."\r\n";
		$data .= '<copyright>WiSH.vn</copyright>'."\r\n";
		//$data .= '<generator>WiSH.vn:http://WiSH.vn/RSS</generator>'."\r\n";
		$pubDate = time() - 10*24*60*60;
		$data .= '<pubDate>'.date("D, j M Y G:i:s O",$pubDate).'</pubDate>'."\r\n";
		$data .= '<lastBuildDate>'.date("D, j M Y G:i:s O").'</lastBuildDate>'."\r\n";
		foreach((array)$newsList as $news){
			$pubDate = strtotime($news['date_publish_updated']);
			$url = WEB_PATH.'/tin-tuc/chi-tiet/'.$news['id_news'].'/'.$objConvert->utf8_to_url($news['title_vn']).'.html';
			$data .= '<item>'."\r\n";
			$data .= '<title>'.$news['title_vn'].'</title>'."\r\n";
			$data .= '<link>'.$url.'</link>'."\r\n";
			$data .= '<description>'.$news['desc_vn'].'</description>'."\r\n";
			$data .= '<pubDate>'.date("D, j M Y G:i:s O",$pubDate).'</pubDate>'."\r\n";
			$data .= '</item>'."\r\n";
		}

		$data .= '</channel>'."\r\n\r\n";

		$data .= '</rss>'."\r\n";

		return $data;
	}

	private function _getNewsForRSS(){
		$sql  = "SELECT * FROM news WHERE facebook_publish = 1 AND date(date_publish_updated) = date('".date('Y-m-d')."') ORDER BY date_publish_updated DESC";
		return $this->_db->fetchAll($sql);
	}

	public function setRSS($ids,$rss){
		@$auth 			= Zend_Auth::getInstance();
		$user 			= @$auth->getStorage()->read();
		$wishid			= $user->wishid;

		for($i=0;$i<sizeof($ids);$i++){
			$newsId = $ids[$i];
			if(isset($rss[$i])){
				$publish = 1;
			}else{
				$publish = 0;
			}
			$this->updateNews($publish, $newsId, $wishid);
		}
		return true;
	}

	public function setNewsKeywords($ids,$keywords){
		$this->_name = "news";
		for($i=0;$i<sizeof($ids);$i++){
			$newsId = $ids[$i];
			if(isset($keywords[$i])){
				$data = array('seo_keywords'=>$keywords[$i]);
				$this->update($data, 'id_news='.$newsId);
			}
		}
		$this->_name = "seo_page";
		return true;
	}

	function updateNews($publish,$newsId,$wishid){
		$data = array();
		$data['facebook_publish'] = $publish;
		$data['date_publish_updated'] = date('Y-m-d H:i:s');
		$data['admin_publish'] = $wishid;
		$this->_name = "news";
		$this->update($data, "id_news = ".(int)$newsId);
		$this->_name = "seo_page";
	}

	private function _countNotIndexed($someDayAgo){
		$sql = "SELECT COUNT(seopage_id)
				FROM seo_page
				WHERE reference_news_id > 0 AND is_google_index = 0 AND date(date_updated) <= date('".$someDayAgo."')";
		return $this->_db->fetchOne($sql);
	}

	public function resetIndexing($timeAgo = 7){
		$someDayAgo = date('Y-m-d',time() - $timeAgo*24*60*60);
		$totalKey = $this->_countNotIndexed($someDayAgo);
		$sql = "UPDATE seo_page
				SET reference_news_id = 0, secondary_keyword = '', seo_tags = '',tag_description = '',
				title = '', content = '',is_group_check = 0, total_mark = 0, is_mark = 0, total_same_key = 0,priority = 5
				WHERE reference_news_id > 0 AND is_google_index = 0 AND date(date_updated) <= date('".$someDayAgo."')";
		$this->_db->query($sql);

		return $totalKey;
	}

	public function updateGoogleIndexing($ids = array(),$isReset = 0){
		if(is_array($ids) && sizeof($ids) >0){
			$sql = "UPDATE seo_page SET is_google_index = 1 WHERE seopage_id IN (".implode(',', $ids).")";
			$this->_db->query($sql);
		}
		return true;
	}

	public function autoMark($limit=100){
		/*
		 * Hệ thống tự động tìm kiếm những từ khóa có trong hệ thống
		* Sau đó so sánh với các bài viết
		* Nếu từ khóa nằm trong tiêu đề của bài viết, thì đánh dấu là bài viết đó có từ khóa liên quan.
		* */
		mb_internal_encoding('UTF-8');
		$keys	  	= $this->_getKeywordForMark($limit);
		$count		= 0;
		if(is_array($keys) && sizeof($keys) >0){
			foreach($keys as $key){
				$totalMark 			= 0;
				$seopage_id 		= $key['seopage_id'];
				$tag_title 			= mb_strtolower(trim($key['tag_title']));
				$secondary_keyword  = mb_strtolower(trim($key['secondary_keyword']));
				if($tag_title) $totalMark 	= $this->_countNewsForMark($tag_title);
				if($totalMark == 0 && $secondary_keyword) $totalMark = $this->_countNewsForMark($secondary_keyword);
				if($totalMark > 0) $count++;
				$totalSameKey	= $this->_countSameKey($tag_title);
				$data = array('total_mark'=>$totalMark,'is_mark'=>1,'total_same_key'=>$totalSameKey);
				$this->update($data, 'seopage_id = '.(int)$seopage_id);
			}
		}else{
			$this->_updateIsMark();
		}
		return $count;
	}

	private function _countSameKey($keyword){
		$sql  = "SELECT COUNT(seopage_id)
		FROM seo_page
		WHERE tag_title LIKE '%$keyword%' AND reference_news_id = 0 AND is_keyword = 1 AND priority > 1";
		return $this->_db->fetchOne($sql);
	}

	private function _updateIsMark(){
		$sql  = "UPDATE seo_page SET is_mark = 0 WHERE is_mark = 1 AND total_mark = 0 AND reference_news_id = 0 ";
		$this->_db->query($sql);
	}

	private function _getKeywordForMark($limit = 100){
		$sql  = "SELECT seopage_id,tag_title,secondary_keyword
		FROM seo_page
		WHERE is_mark = 0 AND reference_news_id = 0
		ORDER BY monthly_search DESC LIMIT $limit";
		return $this->_db->fetchAll($sql);
	}

	private function _countNewsForMark($keyword){
		$keyword = addslashes($keyword);
		$sql 	= "SELECT COUNT('id_news')
		FROM news
		WHERE status='active' AND title_vn REGEXP BINARY '$keyword' OR title_vn REGEXP BINARY '".$this->mb_ucfirst($keyword)."'";
		return $this->_db->fetchOne($sql);
	}

	function mb_ucfirst($str) {
		$fc = mb_strtoupper(mb_substr($str, 0, 1));
		return $fc.mb_substr($str, 1);
	}

	public function autoLinkContent($limit){
		/*
		 * Hệ thống tự động tìm kiếm các từ khóa đã được đánh dấu
		* Tự động tìm kiếm các bài viết phù hợp, và ráp nối lại
		* Nếu ok thì bài viết sẽ được tự động đăng lên.
		*
		* */
		@$auth 			= Zend_Auth::getInstance();
		$user 			= @$auth->getStorage()->read();
		$wishid			= @$user->wishid;
		$countLinked = 0;
		$noLinks = $this->getNoLinkSeopage($limit);
		foreach((array)$noLinks as $seo){
			$seopageId 		= $seo['seopage_id'];
			$keyword1 		= $seo['tag_title'];
			$keyword2 		= $seo['secondary_keyword'];
			$title 			= trim($seo['title']);
			$news 			= $this->getNewsIdForLink($keyword1);
			if(!is_array($news) || sizeof($news) <= 0){
				$news = $this->getNewsIdForLink($keyword2);
			}
			if(is_array($news) && sizeof($news) >0){
				$referenceId	= $news['id_news'];
				$newsTitle		= $news['title_vn'];

				if(!$title) $title = $keyword1;

				$data 			= array();
				$data['is_autolink'] 	   = 1;
				$data['link_type_id'] 	   = 2;
				if($referenceId >0){
					$countLinked++;
					$data['reference_news_id'] = $referenceId;
					$data['tag_description']   = $this->getSeoAutoContent($keyword1,1);
					$data['title']   		   = $title;
					if($wishid >0) $data['admin_update_id']   = $wishid;
					$data['date_updated'] 	   = date('Y-m-d H:i:s');
				}
				$this->update($data, 'seopage_id = '.$seopageId);
			}
		}
		return $countLinked;
	}

	public function getSeoAutoContent($keyword,$autoType){
		/*
		 * $autoType = 1 -> Tag description
		* $autoType = 2 -> Trích dẫn ngắn của tin
		* $autoType = 3 -> Comment của tin
		* */
		$sql 		= "SELECT auto_id,auto_content	FROM seo_auto	WHERE  auto_type_id = ?";
		$autoList 	= $this->_db->fetchAll($sql,array($autoType));
		$index 		= rand(0,sizeof($autoList)-1);
		$autoContent = $autoList[$index]['auto_content'];
		$autoContent = str_replace('__keyword__', $keyword, $autoContent);
		return $autoContent;
	}

	public function getNewsIdForLink($keyword){
		mb_internal_encoding('UTF-8');
		$keyword = strtolower($keyword);
		$keyword = addslashes($keyword);
		// Lay tat ca cac tin co title gan giong tu khoa
		$sql = "SELECT id_news,title_vn FROM news WHERE `status` = 'active' AND title_vn LIKE '%$keyword%'";
		$newsList = $this->_db->fetchAll($sql);

		$arrIds = array();
		$arrNews = array();
		// Kiem tra toan bo danh sach tin
		foreach((array)$newsList as $news){
			$title 			= mb_strtolower(trim($news['title_vn']));
			$id 			= $news['id_news'];
			if(@strpos($title,$keyword) !== false && !in_array($id, $arrIds)){
				$arrIds[] = $id;
				$arrNews[] = $news;
			}
		}
		if(is_array($arrNews) && sizeof($arrNews) >0){
			return $arrNews[0];
		}else{
			return $arrNews;
		}
	}

	public function getNoLinkSeopage($limit){
		/**
		 * Dieu kien xac dinh chua ket noi
		 * reference_news_id = 0 -> Chua ket noi voi bai viet nao
		 * is_keyword = 1 -> La tu khoa
		 * priority = 1 -> Da duoc set do uu tien bang tay, admin da kiem duyet la tu khoa roi.
		 *
		 */
		$sql = "SELECT seopage_id,tag_title,secondary_keyword,title
		FROM seo_page
		WHERE  reference_news_id = 0 AND is_keyword = 1 AND priority = 1
		ORDER BY monthly_search DESC LIMIT $limit";
		return $this->_db->fetchAll($sql);
	}

	public function setKeywords($isKeyword,$idList){
		$sql = "UPDATE seo_page set is_keyword = ".(int)$isKeyword." WHERE seopage_id IN (".implode(',', $idList).")";
		$this->_db->query($sql);
	}

	public function setSeoDatas($seoDatas){
		foreach($seoDatas as $item){
			$keyword 	= trim($item['secondary_keyword']);
			$tags	 	= trim($item['seo_tags']);
			$seopageId 	= $item['seopage_id'];
			$data = array('secondary_keyword'=>$keyword,'seo_tags'=>$tags,'date_updated'=>date('Y-m-d H:i:s'));
			if($keyword || $tags) $data['priority'] = 1;
			$this->update($data, 'seopage_id='.$seopageId);
		}
		return 1;
	}

	public function setPriority($priority,$idList){
		$sql = "UPDATE seo_page set priority = ".(int)$priority." WHERE seopage_id IN (".implode(',', $idList).")";
		$this->_db->query($sql);
	}

	public function getAllSeoPage(){
		$sql = " SELECT * FROM seo_page WHERE reference_news_id > 0 AND date(date_updated) = date('".date('Y-m-d')."')";
		return $this->_db->fetchAll($sql);
	}

	public function updateKeywords($keywords){
		foreach((array)$keywords as $item){
			$keyword 		= trim($item[0]);
			$competition 	= trim($item[1]);
			$monthlySearch 	= trim($item[2]);
			$data 						= array();
			$data['competition'] 		= $competition;
			$data['monthly_search'] 	= $monthlySearch;
			$seopageId 					= $this->checkExistsKeyword($keyword);
			if($seopageId > 0){
				$this->update($data, "seopage_id = ".(int)$seopageId);
			}else{
				$data['tag_title'] 			= $keyword;
				$this->insert($data);
			}
		}
		return 1;
	}

	public function checkExistsKeyword($keyword,$action="insert",$seopageId = null){
		$keyword = strtolower(trim($keyword));
		if($action == 'insert'){
			$sql = "SELECT seopage_id FROM seo_page WHERE tag_title REGEXP BINARY '^$keyword$' LIMIT 1";
			return  (int)$this->_db->fetchOne($sql);
		}else{
			$sql = "SELECT seopage_id FROM seo_page WHERE tag_title REGEXP BINARY '^$keyword$' AND seopage_id <> ?  LIMIT 1";
			return  (int)$this->_db->fetchOne($sql,array($seopageId));
		}
	}

	public function updateData($data,$seopageId){
		$tagTitle = trim($data['tag_title']);
		if($tagTitle != '' && !$this->checkExistsKeyword($tagTitle,'update',$seopageId)){
			$this->update($data, "seopage_id=".(int)$seopageId);
			return $seopageId;
		}else{
			return "-1";
		}
	}

	public function addData($data){
		$tagTitle = trim($data['tag_title']);
		if($tagTitle != '' && !$this->checkExistsKeyword($tagTitle)){
			$this->insert($data);
			return $this->getMaxId();
		}else{
			return "-1";
		}
		$this->insert($data);
		return $this->getMaxId();
	}

	public function getMaxId(){
		$sql = "SELECT MAX(seopage_id) FROM seo_page";
		return  (int)$this->_db->fetchOne($sql);
	}

	public function checkExistsPage($seopageId){
		$sql = " SELECT COUNT(seopage_id) FROM seo_page WHERE reference_news_id >0 AND is_keyword = 1 AND seopage_id= ".(int)$seopageId;
		return $this->_db->fetchOne($sql);
	}

	public function getSeopage($seopageId,$filter = array()) {
		$sql = " SELECT * FROM seo_page WHERE is_keyword = 1 AND seopage_id= ".(int)$seopageId;
		$seoData = $this->_db->fetchRow($sql);
		if(isset($filter['getRelatedNews'])) $seoData['relatedNews'] = $this->getRelatedNews($seoData,10);
		if(isset($filter['getOtherNews'])) $seoData['otherNews'] = $this->getOtherSeoNews(50);
		return $seoData;
	}

	private function getOtherSeoNews($limit){
		$arrIds = $this->getSeoPageIds($limit);
		$sql = "SELECT * FROM seo_page WHERE reference_news_id >0 AND seopage_id in (".implode(',',$arrIds).")";
		return $this->_db->fetchAll($sql);
	}

	public function getSeoPageIds($limit){
		$sql = "SELECT seopage_id FROM seo_page WHERE reference_news_id >0";
		$ids = $this->_db->fetchAll($sql);
		if(sizeof($ids) <= $limit) $limit = sizeof($ids);
		$arrIds = array();
		while(sizeof($arrIds) < $limit){
			$index = rand(0,sizeof($ids) - 1);
			if(!in_array($ids[$index]['seopage_id'], $arrIds)) $arrIds[] = $ids[$index]['seopage_id'];
		}
		//echo "<pre>";
		//print_r($arrIds);die();
		return $arrIds;
	}

	private function getRelatedNews($seoData,$limit = 10){
		$keywords 				= array();
		$seoTags  				= trim($seoData['seo_tags']);
		$secondaryKeyword  		= trim($seoData['secondary_keyword']);
		if($seoTags) $keywords 	= explode(',', $seoTags);
		$keywords[] 			= $seoData['tag_title'];
		if($secondaryKeyword) $keywords[] = $secondaryKeyword;
		$sqlLike = null;
		foreach((array)$keywords as $keyword){
			$sqlLike .= " title_vn LIKE '%$keyword%' OR ";
		}
		$sqlLike = trim(substr($sqlLike, 0, -4));
		$sql = " SELECT * FROM news WHERE ($sqlLike)";
		$newsList = $this->_db->fetchAll($sql);

		$arrIds = array();
		$arrNews = array();
		$i = 0;
		if(sizeof($newsList) <= $limit) $limit = sizeof($newsList);
		foreach($newsList as $news){
			$title 	= $news['title_vn'];
			$id 	= $news['id_news'];
			$title	= strtolower($title);
			foreach((array)$keywords as $keyword){
				$keyword = strtolower($keyword);
				if(strpos($title,$keyword) !== false && !in_array($id, $arrIds)){
					$i++;
					if($i <= $limit){
						$arrNews[] = $news;
						$arrIds[] = $id;
					}
				}
			}
		}
		return $arrNews;
	}


	public function getSeopageByTagTitle($url) {
		$sql = " SELECT * FROM seo_page WHERE tag_title = ? LIMIT 1 ";
		return $this->_db->fetchRow($sql,array($url));
	}

	public function getListSeopage_nb($filter = array()) {
		$sqlPlus = $this->getListSeopage_sqlPlus($filter);
		$sql = "SELECT COUNT(sp.seopage_id)
		FROM seo_page sp
		LEFT JOIN news ON news.id_news = sp.reference_news_id
		WHERE 1=1 $sqlPlus";
		return $this->_db->fetchOne($sql);
	}

	public function getLatestLink($showId = 2,$limit = 20){
		$sql = "SELECT * FROM seo_page WHERE is_keyword = 1 AND reference_news_id > 0 ORDER BY date_updated DESC LIMIT ".(int)$limit;
		return $this->_db->fetchAll($sql);
	}

	public function getListSeopage($start=0,$size = 10,$filter = array()) {
		$sqlPlus = $this->getListSeopage_sqlPlus($filter);
		$sqlOrder = $this->getListSeopage_orderBy($filter);
		$sql = "SELECT sp.*, news.title_vn news_title
		FROM seo_page sp
		LEFT JOIN news ON news.id_news = sp.reference_news_id
		WHERE 1=1 $sqlPlus $sqlOrder LIMIT $start,$size";
		//echo $sql;
		return $this->_db->fetchAll($sql);
	}

	private function getListSeopage_orderBy($filter){
		$orderBy 	= trim(@$filter['orderBy']);
		$direction 	= trim(@$filter['direction']);
		if($orderBy && $direction){
			$sqlOrder 	= " ORDER BY $orderBy $direction ";
		}else{
			$sqlOrder 	= " ORDER BY sp.total_same_key DESC, sp.total_mark DESC ";
		}
		return $sqlOrder;
	}

	private function getListSeopage_sqlPlus($filter){
		$sqlPlus = null;
		foreach((array)$filter as $key => $val){
			$key = trim($key);
			$val = trim($val);
			switch($key){
				case 'keyword':
					if($val){
						$val = addslashes($val);
						$sqlPlus .= " AND (sp.tag_title LIKE '%$val%' OR sp.tag_description LIKE '%$val%' OR sp.title LIKE '%$val%' OR sp.content LIKE '%$val%' OR news.title_vn LIKE '%$val%') ";
					}
					break;

				case 'date_updated':
					$sqlPlus .= " AND date(date_updated) = date('$val')";
					break;
				case 'time_ago':
					$sqlPlus .= " AND date(date_updated) < date('".date('Y-m-d')."')";
					break;
				case 'is_keyword':
					$sqlPlus .= " AND is_keyword = ".(int)$val;
					break;
				case 'priority':
					$sqlPlus .= " AND priority = ".(int)$val;
					break;
				case 'no_priority':
					$sqlPlus .= " AND priority > 1 ";
					break;
				case 'is_mark':
					$sqlPlus .= " AND is_mark = ".(int)$val;
					break;
				case 'has_mark':
					$sqlPlus .= " AND total_mark > 0";
					break;
				case 'has_same':
					$sqlPlus .= " AND total_same_key > 0";
					break;
				case 'is_google_index':
					$sqlPlus .= " AND is_google_index = ".(int)$val;
					break;
				case 'indexed':
					$sqlPlus .= " AND sp.is_google_index = 1 AND sp.reference_news_id >0 ";
					break;
				case 'not_index':
					$sqlPlus .= " AND priority = 1 AND sp.is_google_index = 0 AND sp.reference_news_id >0 ";
					break;
				case 'has_news':
					$sqlPlus .= " AND sp.reference_news_id >0 ";
					break;
				case 'reference_news_id':
					$sqlPlus .= " AND reference_news_id = ".(int)$val;
					break;
				case 'news_linked':
					$sqlPlus .= " AND reference_news_id > 0";
					break;
				case 'news_no_link':
					$sqlPlus .= " AND reference_news_id = 0";
					break;
				case 'has_visit':
					$sqlPlus .= " AND visited > 0";
					break;
				case 'monthly_search_from':
					if((int)$val >0) $sqlPlus .= " AND monthly_search >= ".$val;
					break;
				case 'monthly_search_to':
					if((int)$val >0) $sqlPlus .= " AND monthly_search <= ".$val;
					break;
				case 'competition_from':
					if((int)$val >0) $sqlPlus .= " AND competition >= ".$val;
					break;
				case 'competition_to':
					if((int)$val >0) $sqlPlus .= " AND competition <= ".$val;
					break;
				case 'visited_from':
					if((int)$val >0) $sqlPlus .= " AND visited >= ".$val;
					break;
				case 'visited_to':
					if((int)$val >0) $sqlPlus .= " AND visited <= ".$val;
					break;
				case 'same_from':
					if((int)$val >0) $sqlPlus .= " AND total_same_key >= ".$val;
					break;
				case 'same_to':
					if((int)$val >0) $sqlPlus .= " AND total_same_key <= ".$val;
					break;
				case 'char_from':
					if((int)$val >0) $sqlPlus .= " AND length(tag_title) >= ".$val;
					break;
				case 'char_to':
					if((int)$val >0) $sqlPlus .= " AND length(tag_title) <= ".$val;
					break;

			}
		}
		return $sqlPlus;
	}



	// For news

	public function getListNews_nb($filter = array()) {
		$sqlPlus 	= $this->getListNews_sqlPlus($filter);
		$sqlJoin	= null;
		$searchFor  = trim(@$filter['search_for']);
		if($searchFor == 'connected'){
			$sqlJoin = ' INNER JOIN seo_page sp ON sp.reference_news_id = news.id_news';
		}
		$sql 		= "SELECT news.id_news
		FROM news $sqlJoin
		WHERE news.status='active' $sqlPlus GROUP BY news.id_news ";
		$idList = $this->_db->fetchAll($sql);
		return sizeof($idList);
	}

	public function getListNews($start=0,$size = 10,$filter = array()) {
		$sqlPlus 	= $this->getListNews_sqlPlus($filter);
		$sqlJoin	= null;
		$searchFor  = trim(@$filter['search_for']);
		if($searchFor == 'connected'){
			$sqlJoin = ' INNER JOIN seo_page sp ON sp.reference_news_id = news.id_news';
		}
		$sql 		= "SELECT news.id_news newsId,news.title_vn newsTitle, news.desc_vn description,news.pictrue,
		news.created,news.facebook_publish rss, news.seo_keywords
		FROM news
		$sqlJoin
		WHERE news.status='active' $sqlPlus GROUP BY news.id_news ORDER BY news.created DESC LIMIT $start,$size";
		//echo $sql;
		return $this->_db->fetchAll($sql);
	}

	private function getListNews_sqlPlus($filter){
		$sqlPlus = null;
		foreach((array)$filter as $key => $val){
			$key = trim($key);
			$val = trim($val);
			switch($key){
				case 'denied_ids':
					if($val){
						$sqlPlus .= " AND news.id_news NOT IN($val)";
					}
					break;
				case 'keyword':
					if($val){
						$sqlPlus .= " AND (news.title_vn LIKE '%$val%') ";
					}
					break;
				case 'search_for':
					if($val == 'not_connected'){
						$sqlPlus .= " AND news.id_news NOT IN (SELECT reference_news_id FROM seo_page)";
					}elseif($val == 'has_keys'){
						$sqlPlus .= " AND (news.seo_keywords <> '') ";
					}elseif($val == 'no_keys'){
						$sqlPlus .= " AND (news.seo_keywords = '' OR news.seo_keywords is null) ";
					}
					break;
			}
		}
		return $sqlPlus;
	}

	public function updateSameInfo($keywordType = 1){
		/*
		 * $keywordType = 1; // Từ khóa có bài viết
		* $keywordType = 2; // Từ khóa ưu tiên
		* $keywordType = 3; // Từ khóa bình thường
		* $keywordType = 4; // Không phải từ khóa
		* $keywordType = 5; // Không áp dụng bộ lọc
		* $keywordType = 6; // Google đã index
		* $keywordType = 7; // Google chưa index
		* */

		switch($keywordType){
			case 1:
				$this->_updateKeyHasNews();
				break;
			case 2:
				break;
		}
	}

	private function _updateKeyHasNews(){
		$sql = "SELECT seopage_id,tag_title
				FROM seo_page
				WHERE reference_news_id = 0 AND is_keyword = 1 AND is_mark = 1 AND priority > 1 AND total_mark > 0";
		$seoList = $this->_db->fetchAll($sql);
		foreach((array)$seoList as $seo){
			$seopage_id 	= $seo['seopage_id'];
			$tag_title 		= $seo['tag_title'];
			$total_same_key = $this->_countSameKey($tag_title);
			$data = array('total_same_key'=>$total_same_key);
			$this->update($data, "seopage_id=".$seopage_id);
		}
	}

}

?>
